<template>
  <div id="trendsHome"
       v-loading="loading"
       element-loading-text="Loading"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)"
   >
    <div class="trends-header">
      <el-tag :key="tag"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)">
        {{tag}}
      </el-tag>
      <el-input class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm">
      </el-input>
      <el-button v-else
                 class="button-new-tag"
                 size="small"
                 @click="showInput">+ Add Words</el-button>
      <el-button type="primary"
                 @click="search">OK</el-button>
      <div class="fr">
        <el-radio-group v-model="time"
                        @change="timeChange">
          <el-radio-button v-for="item in timeRanges"
                           :key="item.id"
                           :label="item.id"
                           border>{{item.label}}</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <f-scroll :scrollStyle="wrapStyle">
      <div class="trends-body"
           v-if="dataShow">
        <el-card>
          <div class="line-chart">
            <div class="line-chart-title">
              Trend of heat change over time
            </div>
            <div class="chart">
              <div class="left">
                <div id="avg"></div>
              </div>
              <div class="right">
                <div id="lineChart"></div>
              </div>
            </div>
          </div>
        </el-card>
        <!-- <el-card>
        <div class="map-chart">
          <div class="line-chart-title">
            Search by area
          </div>
          <div id="mapChart">

          </div>
        </div>
      </el-card> -->
        <el-card v-for="(item,index) in  rankedList"
                 :key="index">
          <div class="line-chart-title">
            {{ dynamicTags[index]}}
          </div>
          <div class="wrap">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="chart">
                  <div :id="'map'+ index"></div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="rank">
                  <div class="title">Related Querys</div>
                  <ul>
                    <li v-for="item in rankedList[index].rankedKeyword.slice(5 * (rankedList[index].page -1),5 * rankedList[index].page)"
                        :key="item.query">
                      <span>&nbsp;{{item.lquery}}</span>
                      <span class="tr">{{item.value}}</span>
                    </li>
                  </ul>
                  <el-pagination layout="prev, pager, next"
                                 :current-page.sync="rankedList[index].page"
                                 :page-size="5"
                                 :total="rankedList[index].len">
                  </el-pagination>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>
    </f-scroll>
  </div>
</template>

<script>
import {
  trendLineOption,
  trendLineSerie,
  trendBarOption,
  trendBarSerie,
  mapOption,
  mapSerie
} from "@/echart/echart-option";

export default {
  data() {
    return {
      googleUrl: "http://35.229.189.61:7001/",
      // googleUrl: "http://127.0.0.1:7001/",
      dynamicTags: ["Louis Vuitton", "YSL"],
      loading: false,
      inputVisible: false,
      inputValue: "",
      dataShow: false,
      height: 120,
      rankedList: [],
      wrapStyle: {
        height: ""
      },
      timeRanges: [
        {
          id: 3,
          label: "One Month"
        },
        {
          id: 4,
          label: "Three Month"
        },
        {
          id: 5,
          label: "Half Year"
        },
        {
          id: 6,
          label: "One Year"
        }
      ],
      time: 6
    };
  },
  mounted() {
    this.setContentHeight();
    this.search();
  },
  methods: {
    search() {
      this.getData();
    },
    setContentHeight() {
      this.$nextTick(() => {
        let dom = document.querySelector("#trendsHome");
        let len = document.body.clientHeight - dom.offsetTop;
        this.wrapStyle.height = len - 80 + "px";
      });
    },
    timeChange(value) {
      this.getData();
    },
    getData() {
      this.dataShow = false;
      this.loading = true;
      this.$http
        .post(this.googleUrl, {
          keywords: this.dynamicTags,
          time: this.time
        })
        .then(res => {
          this.loading = false;
          this.dataShow = true;
          this.$nextTick(() => {
            // related
            let rankedList = res.relatedQ;
            rankedList.forEach(item => {
              item.page = 1;
              item.len = item.rankedKeyword.length;
              item.rankedKeyword.forEach((item, index) => {
                item.lquery =
                  index +
                  1 +
                  "、" +
                  item.query[0].toUpperCase() +
                  item.query.slice(1);
              });
            });
            this.rankedList = rankedList;
            // avg
            let chart = this.$echarts.init(document.getElementById("avg"));
            let lineChart = this.$echarts.init(
              document.getElementById("lineChart")
            );
            let averages = res.lineData.default.averages;
            let avgSerieArr = [];
            for (let i of averages) {
              avgSerieArr.push(new trendBarSerie([i]));
            }
            let bar = new trendBarOption(this.dynamicTags, avgSerieArr);
            chart.setOption(bar);
            // line-chart
            let timelineData = res.lineData.default.timelineData;
            let xData = timelineData.map(item => item.formattedAxisTime);
            let len = this.dynamicTags.length;
            let tlen = timelineData.length;
            let arrs = [];

            for (let i = 0; i < len; i++) {
              arrs[i] = {};
              arrs[i].data = [];
              arrs[i].name = this.dynamicTags[i];
            }
            for (let i = 0; i < tlen; i++) {
              let data = timelineData[i];
              for (let j = 0; j < data.value.length; j++) {
                arrs[j].data.push(data.value[j]);
              }
            }
            arrs = arrs.map(item => {
              return new trendLineSerie(item.name, item.data);
            });
            let line = new trendLineOption(
              xData,
              arrs,
              timelineData,
              this.dynamicTags
            );
            lineChart.setOption(line);
            this.$nextTick(() => {
              // mapChart
              let color = [
                "#c23531",
                "#2f4554",
                "#61a0a8",
                "#d48265",
                "#91c7ae",
                "#749f83",
                "#ca8622",
                "#bda29a",
                "#6e7074",
                "#546570",
                "#c4ccd3"
              ];
              let mapData = res.mapData.default.geoMapData;
              // mapChart
              // let mapArr = mapData.map(item => {
              //   return [item.geoName, item.value[0]];
              // });
              // mapArr.unshift(["Country", "Popularity"]);
              // google.charts.setOnLoadCallback(
              //   drawRegionsMap(
              //     mapArr,
              //     document.querySelector("#mapChart"),
              //     "#c23531"
              //   )
              // );
              for (let i = 0; i < len; i++) {
                let mapArr = mapData.map(item => {
                  return [item.geoName, item.value[i]];
                });
                mapArr.unshift(["Country", "Popularity"]);
                google.charts.setOnLoadCallback(
                  drawRegionsMap(
                    mapArr,
                    document.querySelector(".chart #map" + i),
                    ["#ededed", color[i]]
                  )
                );
              }

              function drawRegionsMap(mapArr, dom, color) {
                let data = google.visualization.arrayToDataTable(mapArr);
                let options = {
                  legend: "none",
                  backgroundColor: "#fafafa",
                  colorAxis: { colors: color }
                };
                let gchart = new google.visualization.GeoChart(dom);
                gchart.draw(data, options);
              }
            });
          });
        });
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    }
  }
};
</script>

<style lang="scss">
@import "../../assets/styles/mixins.scss";
#trendsHome {
  text-align: left;
  overflow-y: auto;
  overflow-x: hidden;
  .trends-header {
    margin-top: 3px;
    border-bottom: 2px solid #d3d3d8;
    padding-bottom: 10px;
    height: 60px;
    line-height: 60px;
    text-align: left;
    padding-left: 10px;
    box-shadow: 0 1px rgba(255, 255, 255, 0.4);
    .fr {
      margin-right: 20px;
    }
    .el-tag {
      margin-left: 10px;
      border-radius: 0;
      font-size: 16px;
      background-color: white;
      border: none;
      line-height: 38px;
      height: 38px;
    }
    .button-new-tag {
      line-height: 40px !important;
      height: 40px !important;
    }
    .el-tag + .el-tag {
      margin-left: 10px;
    }
    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 32px;
      padding-top: 0;
      padding-bottom: 0;
    }
    .el-button--primary {
      height: 38px;
    }
    .input-new-tag {
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }
  }
  .trends-body {
    padding-left: 10px;
    .line-chart-title {
      text-indent: 20px;
      color: rgba(0, 0, 0, 0.87);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 18px;
      line-height: 56px;
      vertical-align: top;
      border-bottom: 3px solid #e0e0e0;
    }
    .line-chart {
      .left {
        width: 8%;
        display: inline-block;
        height: 300px;
        #avg {
          height: 100%;
        }
      }
      .right {
        width: 90%;
        display: inline-block;
        height: 300px;
        #lineChart {
          height: 100%;
        }
      }
    }
    .el-card {
      margin-top: 10px;
      // padding-bottom: 5px;
      .el-card__body {
        padding: 10px;
      }
      .wrap {
        padding: 10px;
        .chart {
          height: 420px;
          & > div {
            height: 100%;
          }
        }

        .rank {
          @include clearfix();
          height: 420px;
          background-color: #fafafa;
          padding-right: 5px;
          .title {
            height: 70px;
            line-height: 70px;
            font-size: 18px;
            text-indent: 30px;
          }
          .tr {
            text-align: right;
            float: right;
            margin-right: 20px;
          }
          & > ul {
            margin: 0;
            margin-left: 30px;
            padding: 0;
            height: 300px;
            overflow: auto;
            list-style-type: none;
            li {
              text-indent: 5px;
              height: 60px;
              line-height: 60px;
              &:nth-child(2n-1) {
                background-color: #fff;
              }
            }
          }
          .el-pagination {
            text-align: right;
            margin-top: 10px;
            button {
              background-color: #fafafa;
            }
            .el-pager li {
              background-color: #fafafa;
            }
          }
        }
      }
    }
    .map-chart {
      #mapChart {
        height: 390px;
        margin-top: 10px;
      }
    }
  }
}
</style>
